package com.springboot.seckill.service.impl;

import com.springboot.seckill.dataobject.PromoDO;
import com.springboot.seckill.enums.EmPromoConstants;
import com.springboot.seckill.mapper.PromoDOMapper;
import com.springboot.seckill.service.PromoService;
import com.springboot.seckill.service.model.PromoModel;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author: HuangDekai
 * @Date: 2022/3/26 20:53
 * @Version: 1.0
 * @since: jdk11
 */
@Service
public class PromoServiceImpl implements PromoService {
    @Autowired
    private PromoDOMapper promoDOMapper;

    /**
     * 通过商品id获取即将进行或正在进行的秒杀活动
     *
     * @param itemId 商品id
     * @return 商品促销活动模型
     */
    @Override
    public PromoModel getPromoByItemId(Integer itemId) {
        //获取对应商品的秒杀信息
        PromoDO promoDO = promoDOMapper.selectByItemId(itemId);
        if (promoDO == null) {
            return null;
        }

        //dataObject -> model
        PromoModel promoModel = convertFromDataObject(promoDO);

        //判断当前时间是否秒杀活动结束
        if (promoModel.getStartDate().isAfterNow()) {
            promoModel.setStatus(EmPromoConstants.SECKILL_STATUS_START.getValue());
        } else if (promoModel.getEndDate().isBeforeNow()) {
            promoModel.setStatus(EmPromoConstants.SECKILL_STATUS_END.getValue());
        } else {
            promoModel.setStatus(EmPromoConstants.SECKILL_STATUS_UNDERWAY.getValue());
        }

        return promoModel;
    }

    private PromoModel convertFromDataObject(PromoDO promoDO){
        if (promoDO == null) {
            return null;
        }
        PromoModel promoModel = new PromoModel();
        BeanUtils.copyProperties(promoDO, promoModel);
        promoModel.setStartDate(new DateTime(promoDO.getStartDate()));
        promoModel.setEndDate(new DateTime(promoDO.getEndDate()));
        return promoModel;
    }
}
